<?php

namespace core;

use of;
use L;
use model\com;
use common\batchInsert;

class order
{

    /**
     * 描述 : 订单列表
     * 注明 :
     *      返回的状态码一览表
     *          400 : 必填字段为空
     * 作者 : copy
     */
    public static function setOrder($data)
    {
        of::work(null);
        try {
            $formatData = $data['format_data'];
            if (empty($data['created_time'])) {
                $data['created_time'] = date('Y-m-d H:i:s');
                $oData = self::getOrder($formatData['global_order']);
                if (200 == $oData['state']) {
                    $data['created_time'] = $oData['data']['created_time'];
                    $data['state'] = $oData['data']['state'];
                    if (20 == $oData['data']['state']
                        && $formatData['platform_type'] == 'AM') {
                        $data['format_data'] = $oData['data']['format_data'];
                        $data['origin_data'] = $oData['data']['origin_data'];
                    }
                }
            }
            //订单数据
            $originData = json_encode($data['origin_data']);
            $temp = json_encode($data['format_data']);
            $order_data[] = [
                'global_order' => $data['global_order'],
                'platform_order' => $data['platform_order'],
                'format_data' => $temp,
                'origin_data' => $originData,
                'created_time' => $data['created_time'],
                'state' => $data['state'],
                'is_visual' => $data['is_visual']
            ];
            //写入订单数据表
            $sql = batchInsert::insert('order_data', $order_data);
            L::sql($sql, 'order');
            //订单属性数据
            $attr[] = [
                'global_order' => $formatData['global_order'],
                'platform_order' => $formatData['platform_order'],
                'platform_type' => $formatData['platform_type'],
                'payment_time' => $formatData['payment_time'],
                'buyer_user' => com::filterEmoji(addslashes($formatData['buyer_user'])),
                'logistics_type' => $formatData['logistics_type'],
                'receiver_name' => com::filterEmoji(addslashes($formatData['receiver_name'])),
                'account' => $formatData['account'],
                'order_amount' => $formatData['order_amount'],
                'amount_paid' => $formatData['amount_paid'],
                'platform_amount' => $formatData['platform_amount'],
                'state' => $data['state'],
                'is_visual' => $data['is_visual'],
                'created_time' => $data['created_time'],
            ];
            //新建订单有原始信息
            if ($originData) {
                //插入属性数据
                $sql = batchInsert::insert('order_attr', $attr);
                L::sql($sql, 'order');
            }
            of::work(true);
        } catch (\Throwable $exp) {
            of::work($exp);
            return false;
        }
    }

    /**
     * 描述 : 通过拉取报告获取订单列表
     * 注明 :
     *      返回的状态码一览表
     *          400 : 必填字段为空
     * 作者 : copy
     */
    public static function getReportOrders($params)
    {
        of::work(['order']);
        try {
            if (!empty($params['data'])) {//写入订单数据
                foreach ($params['data'] as $key => $val) {
                    $order_site = substr($val['sales-channel'], -2);
                    $site = $params['site'];
                    if (!empty($order_site)) {
                        $site = strtoupper($order_site);
                        if ('OM' == $site) {
                            $site = 'US';
                        }
                    } else {
                        if (strstr($val['merchant-order-id'], $site)) {
                            $site = $params['site'];
                        }
                    }
                    $sql = "SELECT `site`, `account_code`, `account_name`, `account_id` FROM `am_orders` WHERE amazon_order_id = '{$val['amazon-order-id']}' AND seller_sku = '{$val['sku']}'";
                    $row = L::sql($sql, 'order');
                    $data[] = [
                        'amazon_order_id' => $val['amazon-order-id'],
                        'merchant_order_id' => $val['merchant-order-id'],
                        'account_id' => $row[0]['account_id'] ?? $params['account_id'],
                        'account_name' => $row[0]['account_name'] ?? $params['account_name'],
                        'account_code' => $row[0]['account_code'] ?? $params['account_code'],
                        'site' => $row[0]['site'] ?? $site,
                        'purchase_date' => gmdate('Y-m-d H:i:s', strtotime($val['purchase-date'])),//付款时间
                        'last_updated_date' => gmdate('Y-m-d H:i:s', strtotime($val['last-updated-date'])),//更新时间
                        'order_status' => $val['order-status'],//订单状态
                        'fulfillment_channel' => $val['fulfillment-channel'],
                        'sales_channel' => $val['sales-channel'],
                        'order_channel' => $val['order-channel'],
                        'ship_service_level' => $val['ship-service-level'],//物流方式
                        'product_name' => $val['product-name'] ? addslashes($val['product-name']) : '',//产品名称
                        'seller_sku' => $val['sku'],//平台SKU
                        'asin' => $val['asin'],//平台ASIN
                        'item_status' => $val['item-status'],//产品状态
                        'quantity' => $val['quantity'],//产品数量
                        'currency' => $val['currency'],//币种
                        'item_price' => $val['item-price'] ?: 0,//订单金额
                        'item_tax' => $val['item-tax'] ?: 0,//订单税
                        'shipping_price' => $val['shipping-price'] ?: 0,//运费金额
                        'shipping_tax' => $val['shipping-tax'] ?: 0,//运费税

                        'gift_wrap_price' => $val['gift-wrap-price'] ?: 0,//礼品价格
                        'gift_wrap_tax' => $val['gift-wrap-tax'] ?: 0,//礼品税
                        'item_promotion_discount' => $val['item-promotion-discount'] ?: 0,//商品促销折扣
                        'ship_promotion_discount' => $val['ship-promotion-discount'] ?: 0,//运输促销折扣

                        'ship_city' => $val['ship-city'],//收件人城市
                        'ship_state' => $val['ship-state'],//收件人省或州
                        'ship_postal_code' => $val['ship-postal-code'],//收件人邮编
                        'ship_country' => $val['ship-country'],//收件人国家
                        'promotion_ids' => $val['promotion-ids'] ?? '',
                        'is_business_order' => $val['is-business-order'] ?? '',
                        'purchase_order_number' => $val['purchase-order-number'] ?? '',
                        'price_designation' => $val['price-designation'] ?? '',
                        'fulfilled_by' => $val['fulfilled-by'] ?? '',
                        'buyer_company_name' => $val['buyer-company-name'] ?? '',
                        'buyer_tax_registration_country' => $val['buyer-tax-registration-country'] ?? '',
                        'buyer_tax_registration_type' => $val['buyer-tax-registration-type'] ?? '',
                        'is_amazon_invoiced' => $val['is-amazon-invoiced'] ?? '',

                        'vat_exclusive_item_price' => $val['vat-exclusive-item-price'] ?? 0,//增值税
                        'vat_exclusive_shipping_price' => $val['vat-exclusive-shipping-price'] ?? 0,//增值税
                        'vat_exclusive_giftwrap_price' => $val['vat-exclusive-giftwrap-price'] ?? 0,//礼品税
                        'created_by' => 1001
                    ];
                    //插入属性数据
                    $sql = batchInsert::insert('am_orders', $data);
                    L::sql($sql, 'order');
                    //释放内存
                    unset($params['data'][$key]);
                    unset($data);
                }
            }
            of::work(true);
            return true;
        } catch (\Throwable $exp) {
            of::work($exp);
            return false;
        }
    }


    /**
     * 描述 : 获取汇总订单数据
     * 参数 :
     *      globalOrder : 汇总订单号
     * 返回 :
     *      {"state" : 状态码, "data" : 订单数据, "info" : "提示信息"}
     * 注明 :
     *      返回的状态码一览表
     *          200 : 操作成功
     *          401 : 订单不存在
     */
    public static function getOrder($order_id)
    {
        $sql = "SELECT
                    format_data,
                    origin_data,
                    created_time,
                    state
                FROM
                    `order_data` 
                WHERE
                    global_order = '{$order_id}'";
        //查询成功
        if ($data = L::sql($sql, 'order')) {
            $data = &$data[0];
            $data['format_data'] = json_decode($data['format_data'], true);
            $data['origin_data'] = json_decode($data['origin_data'], true);
            $result = array('state' => 200, 'data' => &$data, 'info' => '操作成功');
        } else {
            $result = array('state' => 401, 'info' => '订单不存在');
        }
        return $result;
    }

    //FBA 亚马逊订单配送货件报告
    public function setFulfilledShipmentsData($params)
    {
        return true;
    }

    /*
     * 获取订单信息
     */
    public static function getOrderData($order_id)
    {
        $sql = "SELECT
                    global_order,
                    platform_order,
                    format_data,
                    origin_data,
                    created_time,
                    state
                FROM
                    `order_data` 
                WHERE
                    global_order = '{$order_id}'";
        $data = L::sql($sql, 'order');
        if (!empty($data)) {
            return $data[0];
        }
        return [];
    }
}
